package com.apps.gomdiem.fragment;

import java.util.ArrayList;

import android.app.Activity;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.apps.gomdiem.R;
import com.apps.gomdiem.hardcode.MyHardCode;
import com.apps.gomdiem.helper.GetDirectionsAsyncTask;
import com.apps.gomdiem.helper.GetDirectionsAsyncTask.OnGetDirectionListener;
import com.apps.gomdiem.map.api.GMapV2Direction;
import com.apps.gomdiem.model.Store;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

public class SearchTabFragment extends Fragment implements OnMarkerClickListener{

	
	private ArrayList<Store> mListStore = MyHardCode.getStore();
	
	private GoogleMap googleMap;

	private GMapV2Direction md;
	
	
	LatLng fromPosition = new LatLng(13.687140112679154, 100.53525868803263);
	LatLng toPosition = new LatLng(13.683660045847258, 100.53900808095932);

	private LatLng userLocation;

	private static View root;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		if (root != null) {
	        ViewGroup parent = (ViewGroup) root.getParent();
	        if (parent != null)
	            parent.removeView(root);
	    }
	    try {
	    	root = inflater.inflate(R.layout.search_activity, container, false);
	    } catch (InflateException e) {
	        /* map is already there, just return view as it is */
	    }
		
	    md = new GMapV2Direction();
		return root;
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}
	
	@Override
	public void onStart() {
		super.onStart();
		setUpMapIfNeeded();
	}
	
	/**
	 * Ki?m tra google map và google map ra
	 * @author Kypi221
	 */
	private void setUpMapIfNeeded() {
		
		if(googleMap == null){
			googleMap = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
			if(googleMap != null){
				googleMap.setMyLocationEnabled(true);
				setUpMap();
			}
		}
	}
	
	/**
	 * L?y cache v? trí c?a device s? d?ng l?n cu?i ra show t?m trong khi ch? tính toán v? trí hi?n t?i 
	 * Sau khi l?y du?c v? trí hi?n t?i, s? dùng MyLocationListener d? g?i updateCurrentLocation, update l?i v? trí hi?n t?i
	 */
	private void setUpMap() {
		 googleMap.setOnMarkerClickListener(this);
		
        addMarkersToMap();
        
		// Getting LocationManager object from System Service LOCATION_SERVICE
	      LocationManager locationManager = (LocationManager) getActivity().getSystemService(Activity.LOCATION_SERVICE); 
	      // Creating a criteria object to retrieve provider
	      Criteria criteria = new Criteria(); 
	      // Getting the name of the best provider
	      String provider = locationManager.getBestProvider(criteria, true);
	      // Getting Current Location
	      Location location = locationManager.getLastKnownLocation(provider);
	
	      if(location!=null){
	      	updateCurrentLocation(location);
	      }
	      locationManager.requestLocationUpdates(provider, 20000, 0, new MyLocationListener());

    }
	
	 private void addMarkersToMap() {
	        for (int i = 0; i < mListStore.size(); i++) {
	        	googleMap.addMarker(new MarkerOptions()
	            .position(mListStore.get(i).location)
	            .title(mListStore.get(i).nameStore));
			}
	    }
	 
	 /**
		 * Truy?n vào 1 v? trí, show lên google map
		 * @param location
		 */
		private void updateCurrentLocation(Location location) {
			// Getting latitude of the current location
	        double latitude = location.getLatitude();
	        // Getting longitude of the current location
	        double longitude = location.getLongitude();
	        // Creating a LatLng object for the current location
	        LatLng newLatLng = new LatLng(latitude, longitude);
	        // Showing the current location in Google Map
	        googleMap.moveCamera(CameraUpdateFactory.newLatLng(newLatLng));
	        // Zoom in the Google Map
	        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
	        
	        
		}
		
		@Override
		public boolean onMarkerClick(Marker marker) {
			if(userLocation != null){
				getDirection(userLocation, marker.getPosition());
			}
			else {
					// Getting LocationManager object from System Service LOCATION_SERVICE
			      LocationManager locationManager = (LocationManager) getActivity().getSystemService(Activity.LOCATION_SERVICE); 
			      // Creating a criteria object to retrieve provider
			      Criteria criteria = new Criteria(); 
			      // Getting the name of the best provider
			      String provider = locationManager.getBestProvider(criteria, true);
			      // Getting Current Location
			      Location location = locationManager.getLastKnownLocation(provider);
			
			      if(location!=null){
			      	updateCurrentLocation(location);
			      }
			      locationManager.requestLocationUpdates(provider, 20000, 0, new MyLocationListener());
			}
			return false;
		}
		private OnGetDirectionListener getDirectionCallBack = new OnGetDirectionListener() {
			
			@Override
			public void onGetDirectionComplete(ArrayList<LatLng> directionPoints) {
				 PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);

				    for(int i = 0 ; i < directionPoints.size() ; i++) 
				    {          
				        rectLine.add(directionPoints.get(i));
				    }
				    googleMap.addPolyline(rectLine);
			}
		} ;
		
		private void getDirection(LatLng fromPosition, LatLng toPosition){
			new GetDirectionsAsyncTask(getDirectionCallBack).execute(fromPosition, toPosition);
		}
		
		private class MyLocationListener implements LocationListener{

			@Override
			public void onLocationChanged(Location location) {
				updateCurrentLocation(location);
				userLocation = new LatLng(location.getLatitude(), location.getLongitude());
			}

			@Override
			public void onProviderDisabled(String provider) {}

			@Override
			public void onProviderEnabled(String provider) {}

			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {}
		}
	
}
